<template>
	<view>
		<Address :address='address' @handleAddres='handleAddres'></Address>
		<GoodsItem :item='goodsDetail'></GoodsItem>
		<view class="buy_number">
			<view class="title">
				购买数量
			</view>
			<u-number-box :min='1' :max='goodsDetail.buyStock' v-model="goodsDetail.buyNum" @change="valChange">
			</u-number-box>
		</view>
		<view class="integral_list">
			<view class="integral_item u-border-bottom u-border-top">
				<view class="item">
					<image class="icon" src="../../static/img/jifen-icon.png" mode=""></image>
					积分(共{{integral.integral}}个)
				</view>
				<!-- 单独设置输入框宽度不生效-?添加一个父盒子 -->
				<u-tag :text="availablePoints" plain shape="circle"></u-tag>

			</view>
			<view class="integral_item u-border-bottom">
				<view class="item">
					<image class="icon" src="../../static/img/jifen-icon.png" mode=""></image>
					本商品可用积分{{goodsDetail.integral}}
				</view>
			</view>
			<view class="integral_item u-border-bottom" v-if="goodsDetail.marketType==2">
				<view class="item">
					<image class="icon" src="../../static/img/jifen-icon.png" mode=""></image>
					特价商城免费抵扣金额{{goodsDetail.mallQuota}}
				</view>
				<u-tag :text="freeQuota" plain shape="circle"></u-tag>

			</view>
			<u-field :border-bottom='true' type='textarea' v-model="orderInfo.orderRemarks" label="备注信息" placeholder="请填写备注信息" />
		</view>
		<u-gap height="14" bg-color="#ECECEC"></u-gap>
		<BuyMode v-model="buyType"></BuyMode>
		<view class="submit_btn u-border-top">
			<view class="submit_pic">
				共付款
				<view class="pic_num">
					¥<view class="num_text">{{allPic}}</view>
				</view>
			</view>
			<u-button type="primary" shape="circle" @click="submit">立即购买</u-button>
		</view>
	</view>
</template>

<script>
	import Address from './components/Address.vue'
	import GoodsItem from '@/pages/order/components/OrderGoodsItem.vue'
	import BuyMode from '@/components/ZH-BuyMode/ZH-BuyMode.vue'
	import {
		payment
	} from '@/utils/payment.js'
	export default {
		components: {
			Address,
			GoodsItem,
			BuyMode
		},
		watch: {
			'goodsDetail.buyNum'(val) {
				// this.freeQuota 折扣

				const onePic = this.goodsDetail.skuPrice + this.goodsDetail
					.postAge
				const skuPrice = (this.goodsDetail.buyNum * this.goodsDetail.skuPrice + this.goodsDetail
					.postAge) //数量 价格 邮费
				// const integralPic = integral >= this.integral.integral ? integral :
				// 	this
				// 	.goodsDetail.integral

				const availablePoints = this.goodsDetail.integral > this.integral.integral ? this.integral.integral :
					this.goodsDetail.integral //算出来最终可用积分
				let integral = availablePoints * val //可用积分
				this.availablePoints = integral
				let pciAll = 0
				// this.availablePoints = integral
				// 可用积分0
				if (this.goodsDetail.integral == 0) {

				}
				if (integral > this.integral.integral) {
					this.availablePoints = this.integral.integral
					pciAll = skuPrice - this.availablePoints //总价格
				} else {
					pciAll = skuPrice - integral //总价格
					// this.availablePoints = (integral + pciAll).toFixed(2)
				}

				if (pciAll <= 0) {
					this.allPic = 0
				} else {
					if (this.goodsDetail.mallQuota && this.goodsDetail.marketType == 2) {
						// this.freeQuota = this.goodsDetail.mallQuota
						const mallQuota = pciAll - this.goodsDetail.mallQuota //总价-优惠
						console.log(mallQuota)
						// 小于0 优惠没有用完 总价格就是0
						if (mallQuota <= 0) {
							this.freeQuota = (this.goodsDetail.mallQuota + mallQuota).toFixed(2)
							this.allPic = 0
						} else {
							this.freeQuota = this.goodsDetail.mallQuota
							this.allPic = mallQuota.toFixed(2)
						}

					} else {
						this.allPic = pciAll.toFixed(2)
					}


				}
			}
			// integralNumber() {
			// 	this.integralNumber = 0
			// }
		},
		computed: {
			maxIntegral() {
				if (this.goodsDetail.integral > this.integral.integral) {
					return this.integral.integral
				} else {
					return this.goodsDetail.integral
				}
			},
			// availablePoints: {
			// 	// goodsDetail.integral 可用积分
			// 	// integral.integral 拥有积分
			// 	get() {
			// 		// console.log(val,'get')
			// 		this.availablePoints2 = this.goodsDetail.integral > this.integral.integral ? this.integral
			// 			.integral : this
			// 			.goodsDetail.integral
			// 		return this.availablePoints2
			// 	},
			// 	set(val) {
			// 		console.log(val, 'set')
			// 		// this.availablePoints2 = val
			// 	}

			// },
			// allPic() {

			// 	let pciAll = (this.goodsDetail.buyNum * this.goodsDetail.skuPrice + this.goodsDetail.postAge) - this
			// 		.freeQuota - (this.availablePoints)
			// 	console.log(pciAll, this.availablePoints)
			// 	if (pciAll < 0) {
			// 		this.availablePoints = 0
			// 		console.log(this.availablePoints)
			// 		return 0
			// 	}
			// 	return pciAll.toFixed(2)
			// }
		},

		data() {
			return {
				allPic: 0,
				availablePoints: 0,
				integral: {},
				integralNumber: 0,
				goodsDetail: {},
				address: null,
				buyType: 2,
				freeQuota: 0,

				orderInfo: {
					orderRemarks:'',//备注
					address: '', //收货地址 ,
					businessId: '', // 店铺id ,
					businessName: '', // 店铺名字 ,
					consigneeName: '', //收货人姓名 ,
					consigneePhone: '', //收货人电话 ,
					createTime: '', //创建时间 ,
					expressName: '', //快递公司 ,
					expressNo: '', // 快递单号 ,
					externalNo: '', //第三方订单号 ,
					goodsAttr: '', //商品规格多个英文逗号分开 ,
					goodsId: '', // 商品id ,
					goodsImg: '', //商品图片 ,
					goodsMoney: '', // 商品总价格 ,
					goodsNum: '', //商品数量 ,
					goodsTitle: '', //商品标题 ,
					id: '', // 主键id ,
					integral: '', // 使用积分 不用则传0 ,
					isComment: '', //是否评价 0 无法评价 1 待评价 2 已评价,
					isDelete: '', //是否删除 1 是 2 否,
					isPay: '', //是否支付 1 是 2 否,
					orderCode: '', //订单编号,
					orderStatus: '', //订单状态 1 已完成 2 待支付 3 待发货 4 待收货 5 已取消 6 售后订单 7 待自提,
					payTime: '', //支付时间,
					payType: '', //支付方式 1 微信 2 支付宝,
					totalMoney: '', //实际支付总价格,
					userId: '', //用户id
					freeQuota: this.freeQuota

				},
				userInfo: {}
			};
		},
		async onShow() {
			this.address = await this.getReceivingAddress()
		},
		async onLoad(e) {
			const integral = await this.$u.api.myIntegralDetails()
			// integral.integral = 4000
			this.integral = integral
			const userInfo = this.cache.getCache('userInfo')
			if (userInfo) {
				this.userInfo = userInfo
			}
			if (e && e.details) {


				this.goodsDetail = JSON.parse(e.details)
				console.log(this.goodsDetail, '商品详情')
				// this.goodsDetail.integral = 0
				// this.goodsDetail.skuPrice = 1900
				// this.goodsDetail.mallQuota = 100
			}
			// 是否是从地址页面跳转过来的
			if (e && e.address) {
				this.address = JSON.parse(e.address)
			} else {
				this.address = await this.getReceivingAddress()
			}
			console.log(this.address, '是否有默认地址')

		},
		methods: {
			changeIntegraQuota(val) {
				if (this.allPic < 0) {
					uni.showToast({
						title: '抵扣金额不得大于商品总金额',
						icon: 'none'
					})
					this.freeQuota = 0
				}
			},
			changeIntegra(val) {
				if (this.allPic < 0) {
					uni.showToast({
						title: '抵扣金额不得大于商品总金额',
						icon: 'none'
					})
					this.integralNumber = 0
				}
			},
			async submit() {
				if (!this.address) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					})
					return
				}
				const orderInfo = {
					address: this.address.location + this.address.street, //收货地址 ,
					businessId: this.goodsDetail.businessId, // 店铺id ,
					businessName: this.goodsDetail.appBusinessName, // 店铺名字 ,
					consigneeName: this.address.contactName, //收货人姓名 ,
					consigneePhone: this.address.contactPhone, //收货人电话 ,
					createTime: '', //创建时间 ,
					expressName: '', //快递公司 ,
					expressNo: '', // 快递单号 ,
					externalNo: '', //第三方订单号 ,
					goodsAttr: this.goodsDetail.skuName, //商品规格多个英文逗号分开 ,
					goodsId: this.goodsDetail.id, // 商品id ,
					goodsImg: this.goodsDetail.imgUrl, //商品图片 ,
					goodsMoney: this.allPic, // 商品总价格 ,
					goodsNum: this.goodsDetail.buyNum, //商品数量 ,
					goodsTitle: this.goodsDetail.title, //商品标题 ,
					id: '', // 主键id ,
					integral: this.availablePoints || 0, // 使用积分 不用则传0 ,
					isComment: '', //是否评价 0 无法评价 1 待评价 2 已评价,
					isDelete: '', //是否删除 1 是 2 否,
					isPay: '', //是否支付 1 是 2 否,
					orderCode: '', //订单编号,
					orderRemarks: this.orderInfo.orderRemarks, //订单备注,
					orderStatus: '', //订单状态 1 已完成 2 待支付 3 待发货 4 待收货 5 已取消 6 售后订单 7 待自提,
					payTime: '', //支付时间,
					payType: this.buyType, //支付方式 1 微信 2 支付宝,
					totalMoney: this.allPic, //实际支付总价格,
					userId: this.userInfo.id, //用户id
					freeQuota: this.freeQuota //免费抵扣额度
				}
				const orderDetail = await this.$u.api.addOrderInfo(orderInfo)
				// orderAliPay,
				// orderWxPay,
				const {
					id
				} = orderDetail
				let zfbPay = {}
				console.log(this.allPic)
				if (this.allPic == '0.00') {
					await this.$u.api.freePay({
						id,
						type: this.buyType
					})
					uni.showToast({
						title: '支付成功!',
						icon: 'success'
					})
					uni.reLaunch({
						url: '/pages/order/order'
					})
					return
				}
				if (this.buyType == 2) {
					zfbPay = await this.$u.api.orderAliPay({
						id
					})
					// res = res && res.split('&')
					// res.map(item => {
					// 	item = item.split('=')
					// 	zfbPay[item[0]] = item[1]
					// })
				} else if (this.buyType == 1) {
					zfbPay = await this.$u.api.orderWxPay({
						id
					})
				} else {
					await this.$u.api.balancePay({
						id
					})
				}
				try {
					// 支付宝和微信需要走支付接口 余额支付直接跳转
					if (this.buyType == 1 || this.buyType == 2) {
						const res = await payment(this.buyType, zfbPay)
						console.log(res, '支付成功')
					}
					uni.showToast({
						title: '支付成功!',
						icon: 'success'
					})
					uni.reLaunch({
						url: '/pages/order/order'
					})
				} catch (e) {
					uni.showToast({
						title: '支付失败!',
						icon: 'error'
					})
					uni.reLaunch({
						url: '/pages/order/order'
					})
					console.log(e, '支付失败')
				}


			},
			handleAddres() {
				if (this.address) {
					uni.navigateTo({
						url: '/pages/address/address?addressId=' + this.address.id + '&details=' + JSON.stringify(
							this
							.goodsDetail)
					})
				} else {
					uni.navigateTo({
						url: '/pages/address/addAddress?isOrder=' + true + '&goodsDetails=' + JSON.stringify(
							this
							.goodsDetail)
					})
				}

			},
			getReceivingAddress() {
				return new Promise(async (resolve, reject) => {
					const res = await this.$u.api.getReceivingAddress()
					let address = null

					if (res.length !== 0) {
						address = res.find(item => item.isDefault === 1)
						if (!address) {
							address = res[0]
						}
					}
					// console.log(address,'addressaddress')
					resolve(address)
				})

			},
			valChange() {}
		}
	}
</script>

<style lang="scss" scoped>
	.integral_list {
		width: 100%;
		padding: 0 20rpx;
		// margin-bottom: 20rpx;

		.integral_item {
			padding: 20rpx 0;
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 100%;
			font-size: 24rpx;
			color: #575757;

			.available_points {
				background-color: rgb(235, 236, 238);
				// width: 100rpx;
				padding: 0 20rpx;
				height: 100%;
				color: #333;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.item {
				display: flex;
				align-items: center;
			}

			.icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 10rpx;

			}
		}
	}

	.submit_btn {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 750rpx;
		padding: 15rpx 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.submit_pic {
			display: flex;
			align-items: flex-end;
			width: 100%;

			.pic_num {
				color: $u-type-primary;
				font-size: 28rpx;
				margin-left: 10rpx;
				display: flex;
				align-items: flex-end;

				.num_text {
					color: $u-type-primary;
					font-size: 36rpx;
				}
			}
		}
	}

	.buy_number {
		display: flex;
		justify-content: space-between;
		padding: 20rpx;
		padding-top: 10rpx;
	}
</style>
